﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommerceOne.Domains.Entities;

namespace CommerceOne.Domains.UnBoundEnities
{
    /// <summary>
    /// 
    /// </summary>
    public class Cart
    {
        private List<CartProduct> _productLine = new List<CartProduct>();

        /// <summary>
        /// Adds the specified product.
        /// </summary>
        /// <param name="product">The product.</param>
        /// <param name="quantity">The quantity.</param>
        public void Add(Product product, int quantity)
        {
            if (product == null) return;

            CartProduct cartProduct = this._productLine.Where(p => p.Id == product.Id).FirstOrDefault();
            if (cartProduct == null)
            {
                cartProduct = new CartProduct();
                cartProduct.Id = product.Id;
                cartProduct.Name = product.Name;
                cartProduct.Price = product.EnablePrice2 ? product.Price2.Value : product.Price1.Value;
                cartProduct.SubTotal = cartProduct.Price*quantity;
                cartProduct.Bonus = product.Bonus;
                cartProduct.Quantity = quantity;
                this._productLine.Add(cartProduct);
            }
            else
            {
                cartProduct.Quantity += quantity;
                cartProduct.Price = product.EnablePrice2 ? product.Price2.Value : product.Price1.Value;
                cartProduct.SubTotal = cartProduct.Price*cartProduct.Quantity;
            }
        }

        /// <summary>
        /// Removes the specified product.
        /// </summary>
        /// <param name="product">The product.</param>
        public void Remove(Product product)
        {
            this._productLine.RemoveAll(p => p.Id == product.Id);
        }

        /// <summary>
        /// Computes the total.
        /// </summary>
        /// <returns></returns>
        public decimal ComputeTotal()
        {
            return this._productLine.Sum(p => p.SubTotal);
        }

        /// <summary>
        /// Computes the total item.
        /// </summary>
        /// <returns></returns>
        public int ComputeTotalItem()
        {
            return this._productLine.Sum(p => p.Quantity);
        }

        public List<CartProduct> ProductLine { get { return this._productLine; } }

        /// <summary>
        /// Clears the cart.
        /// </summary>
        public void ClearCart()
        {
            this._productLine = new List<CartProduct>();
        }
    }
}
